﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WpfAppPrismT1.Services;

namespace WpfAppPrismT1;

public partial class App
{
    private static IServiceCollection? _serviceCollection;
    private static IServiceProvider? _serviceProvider;
    private static IContainer? _appContainer;

    public static IServiceProvider ServiceProvider
    {
        get => _serviceProvider!;
        private set => _serviceProvider = value;
    }

    public static IContainer AppContainer
    {
        get
        {
            if (_appContainer == null)
            {
                throw new InvalidOperationException("App Container not init");
            }
            return _appContainer;
        }
        private set
        {
            if (_appContainer != null)
            {
                throw new InvalidOperationException("App Container had been initialized");
            }
            _appContainer = value;
        }
    }

    [STAThread]
    static void Main(string[] args)
    {
        using IHost host = CreateHostBuilder(args).Build();
        ServiceProvider = host.Services;

        host.StartAsync();

        var app = new App();
        app.InitializeComponent();
        app.Run();
    }

    private static IHostBuilder CreateHostBuilder(string[] args)
    {
        var builder = Host.CreateDefaultBuilder(args)
            .ConfigureServices(serviceCollection =>
            {
                // 在这里注册的服务，通过 ServiceProvider 和 AppContainer 都可以拿到
                // 因为 prism 的相关服务，是在 App 启动之后才注册，所以通过 ServiceProvider 就拿不到，需要通过 DryIoc 的 AppContainer 去拿。
                _serviceCollection = serviceCollection;
                ConfigureServicesBeforeAppLaunch(serviceCollection);
            });

        return builder;
    }

    public static T GetService<T>()
        where T : class
    {
        var service = AppContainer.GetService<T>();

        if (service == null)
        {
            throw new InvalidOperationException($"Cannot get service if {typeof(T).Name}");
        }

        return service;
    }
}
